//
//  ICEEMPhotograph.m
//  EasyMoney
//
//  Created by 邓乐 on 2020/1/13.
//  Copyright © 2020 zh. All rights reserved.
//

#import "ICEEMPhotograph.h"
#import "EMDeviceAuthorizationManager.h"
#import "ICEJavaScriptBridge.h"

@interface ICEEMPhotograph () <UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (nonatomic, strong) NSDictionary *params;

@end

@implementation ICEEMPhotograph

+ (instancetype)sharedSingleton {
    static ICEEMPhotograph *_sharedSingleton = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        //不能再使用alloc方法
        //因为已经重写了allocWithZone方法，所以这里要调用父类的分配空间的方法
        _sharedSingleton = [[super allocWithZone:NULL] init];
    });
    return _sharedSingleton;
}

// 防止外部调用alloc 或者 new
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    return [ICEEMPhotograph sharedSingleton];
}

// 防止外部调用copy
- (id)copyWithZone:(nullable NSZone *)zone {
    return [ICEEMPhotograph sharedSingleton];
}

// 防止外部调用mutableCopy
- (id)mutableCopyWithZone:(nullable NSZone *)zone {
    return [ICEEMPhotograph sharedSingleton];
}

- (void)takePhoto:(NSDictionary *)params
{
    self.params = params;
    ICEWebInfo* vcinfo = [params objectForKey:@"vcinfo"];
    [EMDeviceAuthorizationManager popupCameraInVC:vcinfo.vc delegate:self];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    UIImage *img = [UIImage compressImage:image toByte:200*1024];
    NSData *encryptedData = UIImageJPEGRepresentation(img, 1.0);
    NSString* base64EncodedString = [NSString stringWithFormat:@"data:image/jpeg;base64,%@",
    [encryptedData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]];
    NSDictionary *dit = nil;
    if (base64EncodedString.length > 0) {
          dit = @{
                  @"status":@"success",
                  @"image":base64EncodedString,
                  };
    } else {
        dit =  @{
            @"status":@"error_other",
            };
    }
    [ICEJavaScriptBridge sendReslutToJS:dit callInfo:self.params];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    [ICEJavaScriptBridge sendReslutToJS:@{@"status":@"error_cancel"} callInfo:self.params];
}

@end
